﻿using GalaSoft.MvvmLight.Command;
using KJSyncXP.Extensions;
using KJSyncXP.Oracle.Context;
using KJSyncXP.SQLite.Context;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using System.ComponentModel;
using System.Windows.Input;
using KJSyncXP.Sqlite.Model;
using KJSyncXP.Views;

namespace KJSyncXP.ViewModels
{
    public class LoginViewModel : BaseViewModel
    {
        private readonly ILog _logger;
        private readonly AppConfig _appConfig;
        private readonly SqliteDbContext _sqliteCtx;

        private string _account;
        private string _password;
        private bool _canLogin;

        // 账号
        public string Account
        {
            get => _account;
            set
            {
                _account = value;
                RaisePropertyChanged(nameof(Account));
                CheckCanLogin();
            }
        }

        // 密码属性
        public string Password
        {
            get => _password;
            set
            {
                _password = value;
                RaisePropertyChanged(nameof(Password));
                CheckCanLogin();
            }
        }

        // 登录按钮是否可用
        public bool CanLogin
        {
            get => _canLogin;
            set
            {
                _canLogin = value;
                RaisePropertyChanged(nameof(CanLogin));
            }
        }

        // 登录命令
        public RelayCommand LoginCommand { get; private set; }

        // 取消命令
        public RelayCommand CancelCommand { get; private set; }

        public LoginViewModel(ILog log, SqliteDbContext sqliteCtx, AppConfig appConfig)
        {
            _sqliteCtx = sqliteCtx;
            _logger = log;
            _appConfig = appConfig;
            LoginCommand = new RelayCommand(Login, () => CanLogin);
            CancelCommand = new RelayCommand(Cancel);

            CreateAdmin();
            // 初始检查登录按钮状态
            CheckCanLogin();
        }

        // 创建超级管理员
        private void CreateAdmin()
        {
            try
            {
                _sqliteCtx.Db.Transaction(() => {

                    var userlist = _sqliteCtx.Db.Select<User>().Where(u => u.Username == "admin").ToList();
                    if (userlist.Count == 0)
                    {
                        var admin = new User
                        {
                            Useruuid = Guid.NewGuid().ToString(),
                            Username = "admin",
                            Userpwd = "123456",
                            Realname = "admin",
                            Inuse = true,
                            State = 0,
                        };
                        _sqliteCtx.Db.Insert(admin).ExecuteAffrows();


                        var permission = _sqliteCtx.Db.Queryable<Permission>().ToList();
                        var defaultPermissions = new List<Permission>();
                        if (permission.Count == 0)
                        {
                            // 创建默认权限列表
                            defaultPermissions = new List<Permission>
                            {
                                new Permission
                                {
                                    Puuid = "perm_std_query",
                                    Pname = "检测标准查询",
                                    Pkey = "StdQueryPage",
                                    Ptype = "模块",
                                    Plevel = 1,
                                    Pdescription = "检测标准查询模块访问权限",
                                    Remark = "系统基础模块权限",
                                    Inuse = true,
                                    Isshow = true
                                },
                                new Permission
                                {
                                    Puuid = "perm_rejudge_record",
                                    Pname = "结果重判记录",
                                    Pkey = "RejudgeRecordPage",
                                    Ptype = "模块",
                                    Plevel = 1,
                                    Pdescription = "结果重判记录模块访问权限",
                                    Remark = "系统基础模块权限",
                                    Inuse = true,
                                    Isshow = true
                                },
                                new Permission
                                {
                                    Puuid = "perm_std_change_record",
                                    Pname = "标准变更记录",
                                    Pkey = "StdChangeRecordPage",
                                    Ptype = "模块",
                                    Plevel = 1,
                                    Pdescription = "标准变更记录模块访问权限",
                                    Remark = "系统基础模块权限",
                                    Inuse = true,
                                    Isshow = true
                                },
                                new Permission
                                {
                                    Puuid = "perm_check_point",
                                    Pname = "检点",
                                    Pkey = "CheckPointPage",
                                    Ptype = "模块",
                                    Plevel = 2,
                                    Pdescription = "检点",
                                    Remark = "检点",
                                    Inuse = true,
                                    Isshow = true
                                },
                                new Permission
                                {
                                    Puuid = "perm_inspection_result_query",
                                    Pname = "检验结果查询",
                                    Pkey = "InspectionResultQueryPage",
                                    Ptype = "模块",
                                    Plevel = 2,
                                    Pdescription = "检验结果查询",
                                    Remark = "检验结果查询",
                                    Inuse = true,
                                    Isshow = true
                                },

                                new Permission
                                {
                                    Puuid = "perm_system_setting",
                                    Pname = "系统设置",
                                    Pkey = "SystemSettingPage",
                                    Ptype = "模块",
                                    Plevel = 2,
                                    Pdescription = "系统配置模块访问权限",
                                    Remark = "系统管理员权限",
                                    Inuse = true,
                                    Isshow = true
                                },
                                new Permission
                                {
                                    Puuid = "perm_permission_setting",
                                    Pname = "权限设置",
                                    Pkey = "PermissionSettingPage",
                                    Ptype = "模块",
                                    Plevel = 2,
                                    Pdescription = "用户管理模块访问权限",
                                    Remark = "用户管理相关权限",
                                    Inuse = true,
                                    Isshow = true
                                },
                                
                                new Permission
                                {
                                    Puuid = "UserCreate",
                                    Pname = "创建用户",
                                    Pkey = "UserCreate",
                                    Ptype = "操作",
                                    Plevel = null,
                                    Pdescription = "创建用户",
                                    Remark = "创建用户",
                                    Inuse = true,
                                    Isshow = true
                                },
                                new Permission
                                {
                                    Puuid = "UserPwdModify",
                                    Pname = "修改用户口令",
                                    Pkey = "UserPwdModify",
                                    Ptype = "操作",
                                    Plevel = null,
                                    Pdescription = "修改用户口令",
                                    Remark = "修改用户口令",
                                    Inuse = true,
                                    Isshow = true
                                },
                                new Permission
                                {
                                    Puuid = "UserDelete",
                                    Pname = "删除用户",
                                    Pkey = "UserDelete",
                                    Ptype = "操作",
                                    Plevel = null,
                                    Pdescription = "删除用户",
                                    Remark = "删除用户",
                                    Inuse = true,
                                    Isshow = true
                                },
                                 new Permission
                                {
                                    Puuid = "PrecisionCheckPoint",
                                    Pname = "精度检点",
                                    Pkey = "PrecisionCheckPoint",
                                    Ptype = "模块",
                                    Plevel = null,
                                    Pdescription = "精度检点",
                                    Remark = "精度检点",
                                    Inuse = true,
                                    Isshow = true
                                },
                                 new Permission
                                {
                                    Puuid = "CheckPointSettings",
                                    Pname = "检点设置",
                                    Pkey = "CheckPointSettings",
                                    Ptype = "模块",
                                    Plevel = null,
                                    Pdescription = "检点设置",
                                    Remark = "检点设置",
                                    Inuse = true,
                                    Isshow = true
                                },
                                 new Permission
                                {
                                    Puuid = "StartWorkCheckPoint",
                                    Pname = "开班检点",
                                    Pkey = "StartWorkCheckPoint",
                                    Ptype = "模块",
                                    Plevel = null,
                                    Pdescription = "开班检点",
                                    Remark = "开班检点",
                                    Inuse = true,
                                    Isshow = true
                                },
                            };
                            _sqliteCtx.Db.Insert<Permission>(defaultPermissions).ExecuteAffrows();
                        }

                      
                        // 将所有权限给超管
                        //var allPermissions = _sqliteCtx.Db.Select<Permission>().ToList();

                        var userPermissionList = new List<Up>();
                        foreach (var perm in defaultPermissions)
                        {
                            userPermissionList.Add(new Up
                            {
                                Useruuid = admin.Useruuid, // 关联admin的用户标识
                                Puuid = perm.Puuid,        // 关联权限的全局标识
                                Username = "admin",        // 用户名
                                Pname = perm.Pname,        // 权限名称
                                Ptype = perm.Ptype,        // 权限类型（模块/检点等）
                                Description = perm.Pdescription, // 权限描述（截图中为Null，可保持一致）
                                Remark = perm.Remark,      // 权限备注
                                Atype = 1,                 // 类型：1表示“权限”（可按业务定义）
                            });
                        }


                        if (userPermissionList.Count > 0)
                        {
                            _sqliteCtx.Db.Insert(userPermissionList).ExecuteAffrows();
                        }
                    }
                });            
            }
            catch (Exception ex) { 
                _logger.Error(ex); 
            }
        }


        // 检查是否可以登录（账号和密码都不为空）
        private void CheckCanLogin()
        {
            CanLogin = !string.IsNullOrWhiteSpace(Account) && !string.IsNullOrWhiteSpace(Password);
        }

        // 登录逻辑实现
        private void Login()
        {
            try
            {
                var authManager = AuthenticationManager.Instance;
                var res = authManager.Authenticate(Account, Password);

                if (res)
                {
                    // 登录成功，记录日志
                    _logger.Info($"用户登录成功，账号：{Account}");

                    // 关闭登录窗口并返回成功结果
                    var loginWindow = System.Windows.Application.Current.Windows.OfType<Views.pop.LoginWindow>().FirstOrDefault();
                    if (loginWindow != null)
                    {
                        loginWindow.DialogResult = true;
                        loginWindow.Close();
                    }
                }
            }
            catch (Exception ex) { 
                _logger.Error(ex); 
            }


        }

        /*private void Login()
        {
            try
            {
                // 登录验证逻辑
                var user = _sqliteCtx.Db.Select<User>().Where(u => u.Username == Account).First();

                if (user == null)
                {
                    var notification = new CustomNotificationWindow
                    {
                        NotificationTitle = "登录操作提示",
                        NotificationContent = "登录失败，账号不存在"
                    };
                    notification.ShowDialog();
                    return;
                }

                // 密码需要是加密存储的
                if (user.Userpwd != Password)
                {
                    var notification = new CustomNotificationWindow
                    {
                        NotificationTitle = "登录操作提示",
                        NotificationContent = $"登录失败，密码错误，账号：{Account}"
                    };
                    notification.ShowDialog();                  
                    return;
                }

                // 登录成功，记录日志
                _logger.Info($"用户登录成功，账号：{Account}");

                // 保存登录状态（可以根据需要实现）
                SaveLoginState(user);

                // 关闭登录窗口并返回成功结果
                var loginWindow = System.Windows.Application.Current.Windows.OfType<Views.pop.LoginWindow>().FirstOrDefault();
                if (loginWindow != null)
                {
                    loginWindow.DialogResult = true;
                    loginWindow.Close();
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"登录过程中发生错误：{ex.Message}", ex);               
            }
        }*/

        // 取消登录
        private void Cancel()
        {
            var loginWindow = System.Windows.Application.Current.Windows.OfType<Views.pop.LoginWindow>().FirstOrDefault();
            if (loginWindow != null)
            {
                loginWindow.DialogResult = false;
                loginWindow.Close();
            }
        }

        // 保存登录状态
        /*private void SaveLoginState(User user)
        {
            _appConfig.CurrentUser = user.Username;
        }*/
    }
}
